import re
from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from users import constants
from .models import User
from django.conf import settings


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


def get_user_by_account(username):
    """
    :param username: 是手机号或者用户名
    :return: 返回用户
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', username):
            # 帐号为手机号
            user = User.objects.get(mobile=username)
        else:
            # 帐号为用户名
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None
    else:
        print(user)
        return user


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        自定义用户名或手机号认证
        """
        user = get_user_by_account(username)
        print(password)
        if user is not None and user.check_password(password):
            print(user)
            return user


def generate_save_user_token_url(user):
    """使用Itsdangrous保存openID，生成access_token"""
    # serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    # serializer = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    # serializer.dumps(数据), 返回bytes类型
    data = {'user_id': user.id}
    token = serializer.dumps(data)
    token = token.decode()

    # 拼接url地址
    verify_url = settings.EMAIL_ADDR + '?token=' + token

    return verify_url


def check_verify_email_token(token):
    # serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = serializer.loads(token)
        return data['user_id']
    except BadData:
        return None
